package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.RedisData;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.pro.model.ShopModel;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheUtil;
import com.hmdp.utils.RedisConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.babyfish.jimmer.sql.JSqlClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 七倉玲華
 * @since 2022-10-30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate redisTemplate;

    private final CacheUtil cacheUtil;
    private final JSqlClient sqlClient;
    private final ObjectMapper jsonMapper;

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
        //ShopModel shop = queryWithPassThrough(id);
        ShopModel shop = cacheUtil.queryWithPassThrough(CACHE_SHOP_KEY, id, ShopModel.class, (modelId) -> sqlClient.getEntities().findById(ShopModel.class, id), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 使用互斥锁解决缓存穿透
        //ShopModel shop = queryWithMutex(id);

        // 逻辑过期方案
        //Shop shop = queryWithLogicalExpire(id);

        return Result.ok(shop);
    }

    private boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    // solution with mutex (safe)
    public ShopModel queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            try {
                return jsonMapper.readValue(shopJson, ShopModel.class);
            } catch (JsonProcessingException e) {
                log.error("数据不合法");
                return null;
            }
        }
        if ("".equals(shopJson)) {
            return null;
        }
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        ShopModel shop;
        try {
            boolean isLock = tryLock(lockKey);
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            shop = sqlClient.getEntities().findById(ShopModel.class, id);
            if (Objects.isNull(shop)) {
                redisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            try {
                redisTemplate.opsForValue().set(key, jsonMapper.writeValueAsString(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            } catch (JsonProcessingException e) {
                log.error("转换失败");
                return null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }
        return shop;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 使用逻辑过期来解决缓存击穿
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shopJson)) {
            log.info("get null");
            return null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shop;
        }

        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    this.saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }

        return shop;
    }
    // common solution （unsafe）
    /*
    public ShopModel queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            try {
                return jsonMapper.readValue(shopJson, ShopModel.class);
            } catch (JsonProcessingException e) {
                log.error("数据不合法");
                return null;
            }
        }
        if ("".equals(shopJson)) {
            return null;
        }
        ShopModel shop = sqlClient.getEntities().findById(ShopModel.class, id);
        if (Objects.isNull(shop)) {
            redisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        try {
            redisTemplate.opsForValue().set(key, jsonMapper.writeValueAsString(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (JsonProcessingException e) {
            log.error("转换失败");
            return null;
        }
        return shop;
    }
     */

    public void saveShopToRedis(long id, Long expireSeconds) {
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        String json = JSONUtil.toJsonStr(redisData);
        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, json);
    }

    @Override
    @Transactional
    public Result update(ShopModel shop) {
        sqlClient.getEntities().save(shop);
        redisTemplate.delete(CACHE_SHOP_KEY + shop.id());
        return Result.ok();
    }
}
